<!--
  对账管理主页面
  @description 对账管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item
        :label="t('settle.reconciliation.reconciliationDate')"
        prop="reconciliationDate"
      >
        <el-date-picker
          v-model="queryParams.reconciliationDate"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('settle.common.startTime')"
          :end-placeholder="t('settle.common.endTime')"
          value-format="YYYY-MM-DD"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item :label="t('settle.reconciliation.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.reconciliation.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.reconciliation.channelType')" prop="channelType">
        <el-select
          v-model="queryParams.channelType"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.reconciliation.channelType')"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in channelTypeOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="t('settle.reconciliation.reconciliationStatus')"
        prop="reconciliationStatus"
      >
        <el-select
          v-model="queryParams.reconciliationStatus"
          :placeholder="
            t('settle.common.pleaseSelect') + t('settle.reconciliation.reconciliationStatus')
          "
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in reconciliationStatusOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('settle.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('settle.common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleGenerate"
          :loading="generateLoading"
          v-hasPermi="['settle:reconciliation:generate']"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          {{ t('settle.reconciliation.generate') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['settle:reconciliation:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('settle.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column
        :label="t('settle.reconciliation.reconciliationNo')"
        align="center"
        prop="reconciliationNo"
        width="200"
      />
      <el-table-column
        :label="t('settle.reconciliation.reconciliationDate')"
        align="center"
        prop="reconciliationDate"
        width="120"
      />
      <el-table-column
        :label="t('settle.reconciliation.merchantNo')"
        align="center"
        prop="merchantNo"
        width="180"
      />
      <el-table-column
        :label="t('settle.reconciliation.merchantName')"
        align="center"
        prop="merchantName"
        min-width="150"
      />
      <el-table-column
        :label="t('settle.reconciliation.channelType')"
        align="center"
        prop="channelType"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="getChannelTypeTagType(scope.row.channelType)">
            {{ channelTypeOptions[scope.row.channelType] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.reconciliation.totalCount')"
        align="center"
        prop="totalCount"
        width="100"
      />
      <el-table-column
        :label="t('settle.reconciliation.totalAmount')"
        align="center"
        prop="totalAmount"
        width="120"
      >
        <template #default="scope">
          <span class="amount-text">¥{{ (scope.row.totalAmount / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.reconciliation.diffCount')"
        align="center"
        prop="diffCount"
        width="100"
      >
        <template #default="scope">
          <span :class="scope.row.diffCount > 0 ? 'diff-text' : ''">{{ scope.row.diffCount }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.reconciliation.diffAmount')"
        align="center"
        prop="diffAmount"
        width="120"
      >
        <template #default="scope">
          <span :class="scope.row.diffAmount !== 0 ? 'diff-text' : ''">
            ¥{{ (scope.row.diffAmount / 100).toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.reconciliation.reconciliationStatus')"
        align="center"
        prop="reconciliationStatus"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="getReconciliationStatusTagType(scope.row.reconciliationStatus)">
            {{ reconciliationStatusOptions[scope.row.reconciliationStatus] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.common.createTime')"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column
        :label="t('settle.common.operation')"
        align="center"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['settle:reconciliation:query']"
          >
            {{ t('settle.common.view') }}
          </el-button>
          <el-button
            link
            type="success"
            @click="handleDownload(scope.row)"
            v-hasPermi="['settle:reconciliation:download']"
          >
            {{ t('settle.reconciliation.download') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['settle:reconciliation:delete']"
            v-if="scope.row.reconciliationStatus === ReconciliationStatusEnum.PENDING"
          >
            {{ t('settle.common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 对账详情 -->
  <ReconciliationDetail ref="detailRef" />

  <!-- 生成对账单对话框 -->
  <GenerateReconciliationDialog ref="generateDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import {
  getReconciliationFilePageApi,
  deleteReconciliationFileApi,
  downloadReconciliationFileApi,
  exportReconciliationDiffApi
} from '@/api/settle/reconciliation'
import type { ReconciliationVO, ReconciliationPageReqVO } from '@/api/settle/types'
import { ReconciliationStatusEnum, ChannelTypeEnum } from '@/api/settle/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import ReconciliationDetail from './ReconciliationDetail.vue'
import GenerateReconciliationDialog from './GenerateReconciliationDialog.vue'

defineOptions({ name: 'SettleReconciliation' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const generateLoading = ref(false)
const exportLoading = ref(false)

// 列表数据
const list = ref<ReconciliationVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<ReconciliationPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  reconciliationDate: undefined,
  merchantNo: undefined,
  channelType: undefined,
  reconciliationStatus: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const detailRef = ref()
const generateDialogRef = ref()

// 选项数据
const channelTypeOptions = {
  [ChannelTypeEnum.WECHAT]: t('settle.reconciliation.channelTypes.wechat'),
  [ChannelTypeEnum.ALIPAY]: t('settle.reconciliation.channelTypes.alipay'),
  [ChannelTypeEnum.UNIONPAY]: t('settle.reconciliation.channelTypes.unionpay'),
  [ChannelTypeEnum.DIGITAL_RMB]: t('settle.reconciliation.channelTypes.digitalRmb')
}

const reconciliationStatusOptions = {
  [ReconciliationStatusEnum.PENDING]: t('settle.reconciliation.reconciliationStatuses.pending'),
  [ReconciliationStatusEnum.SUCCESS]: t('settle.reconciliation.reconciliationStatuses.success'),
  [ReconciliationStatusEnum.FAILED]: t('settle.reconciliation.reconciliationStatuses.failed'),
  [ReconciliationStatusEnum.PROCESSING]: t(
    'settle.reconciliation.reconciliationStatuses.processing'
  )
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getReconciliationFilePageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询对账列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 生成对账单
 */
const handleGenerate = () => {
  generateDialogRef.value.open()
}

/**
 * 查看详情
 */
const openDetail = (row: ReconciliationVO) => {
  detailRef.value.open(row)
}

/**
 * 下载对账文件
 */
const handleDownload = async (row: ReconciliationVO) => {
  try {
    await downloadReconciliationFileApi(row.id)
    ElMessage.success(t('settle.reconciliation.tips.downloadSuccess'))
  } catch (error) {
    console.error('下载对账文件失败:', error)
  }
}

/**
 * 删除对账单
 */
const handleDelete = async (row: ReconciliationVO) => {
  try {
    await ElMessageBox.confirm(
      t('settle.reconciliation.tips.deleteConfirm'),
      t('settle.common.confirmTitle'),
      {
        confirmButtonText: t('settle.common.confirm'),
        cancelButtonText: t('settle.common.cancel'),
        type: 'warning'
      }
    )

    await deleteReconciliationFileApi(row.id)
    ElMessage.success(t('settle.reconciliation.tips.deleteSuccess'))
    await getList()
  } catch (error) {
    console.error('删除对账单失败:', error)
  }
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportReconciliationDiffApi(queryParams)
    message.success(t('settle.common.exportSuccess'))
  } catch (error) {
    console.error('导出对账数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 标签类型获取函数
const getChannelTypeTagType = (type: number) => {
  const typeMap = {
    [ChannelTypeEnum.WECHAT]: 'success',
    [ChannelTypeEnum.ALIPAY]: 'primary',
    [ChannelTypeEnum.UNIONPAY]: 'warning',
    [ChannelTypeEnum.DIGITAL_RMB]: 'info'
  }
  return typeMap[type] || ''
}

const getReconciliationStatusTagType = (status: number) => {
  const statusMap = {
    [ReconciliationStatusEnum.PENDING]: 'info',
    [ReconciliationStatusEnum.PROCESSING]: 'warning',
    [ReconciliationStatusEnum.SUCCESS]: 'success',
    [ReconciliationStatusEnum.FAILED]: 'danger'
  }
  return statusMap[status] || ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.amount-text {
  color: #409eff;
  font-weight: bold;
}

.diff-text {
  color: #f56c6c;
  font-weight: bold;
}
</style>
